package org.game.gobang.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.SneakyThrows;
import org.game.codec.MsgpackDecoder;
import org.game.codec.MsgpackEncoder;
import org.game.constant.APIConstant;
import org.game.gobang.client.constant.ClientConstant;
import org.game.gobang.client.init.GobangClientInitializer;
import org.game.result.RestResult;
import org.game.result.RestResultBuilder;
import org.game.result.ResultCode;
import org.game.util.JsonUtil;
import org.game.util.MapUtil;
import org.game.util.YamlUtil;

import java.util.Map;
import java.util.Random;

public class GobangClient {
    private int port;
    private String ip;
    private Channel channel;

    public GobangClient(int port, String ip) {
        this.port = port;
        this.ip = ip;
    }

    public static void main(String[] args) throws Exception {
        Map<String, Object> config = YamlUtil.read(GobangClient.class, 2);
        MapUtil.cloneMap(APIConstant.CONFIG, config);
        GobangClient client = new GobangClient((int) APIConstant.CONFIG.get("port"), (String) APIConstant.CONFIG.get("ip"));
        client.start();
    }

    public void start() {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                    .handler(new GobangClientInitializer());

            channel = bootstrap.connect(ip, port).sync().channel();
            ClientConstant.channel = channel;
            channel.closeFuture().sync();
////            new Thread(new Runnable() {
////                @SneakyThrows
////                @Override
////                public void run() {
////                    while (channel.isActive()) {
////                        sendMsg();
////                    }
////                }
////            }).start();
//
//            while (channel.isActive()) {
//                sendMsg();
//            }

        } catch (Exception e) {
            // do something
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

//    public void sendMsg() throws Exception {
//        RestResult restResult = new RestResultBuilder().success(ResultCode.HEARTBEAT_BAG);
//        restResult.setMsg("ping");
//        channel.writeAndFlush(JsonUtil.toJson(restResult));
//        Thread.sleep(4 * 1000);
//    }
}
